package com.nulldev.util.web.HttpServer3.pages.v3;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.JVM.JVM;
import com.nulldev.util.concurrency.threadIt.v4.emapi.ExecutorManager;
import com.nulldev.util.concurrency.threadIt.v4.emapi.cntft.ControllableFutureTask;
import com.nulldev.util.data.Variables;
import com.nulldev.util.web.HttpServer3.Page;
import com.nulldev.util.web.HttpServer3.Response;

public abstract class ASyncHttpPage3 extends HttpPage3 implements Page {

	private static final boolean RUN_REQUEST_ON_EXECUTOR = Arguments.hasArgument("--AsyncHttpPage3.enableRequestDispatch");

	public ASyncHttpPage3(final String id) {
		super(Variables.requireNonNullObject(id, "id"));
	}

	public ASyncHttpPage3(final String id, final boolean captchaExclusion) {
		super(Variables.requireNonNullObject(id, "id"), captchaExclusion);
	}

	@Override
	@Deprecated
	public Response onRequest(final Request request) {
		final ControllableFutureTask<Response> c = new ControllableFutureTask<Response>();
		try {
			if (RUN_REQUEST_ON_EXECUTOR)
				ExecutorManager.globalAsyncSubmit(() -> {
					this.onFutureRequest(request, c);
					return null;
				});
			else
				this.onFutureRequest(request, c);
		} catch (Throwable x) {
			c.fail(x);
		}
		try {
			return (c.completed() && !RUN_REQUEST_ON_EXECUTOR ? c.result() : c.waitTillCompletion());
		} catch (Throwable e) {
			JVM.errorln(e);
			return new Response(503);
		}
	}

	public abstract void onFutureRequest(final Request request, final ControllableFutureTask<Response> r);
}
